//
//  String+Cocoa.swift
//  TTCOM
//
//  Created by Toj on 1/17/23.
//

import Foundation

public extension String {
    
    /**
     * 从from开始截取到末尾
     */
    func cca_subsring(from: Int) -> String {
        guard from >= 0, from < count else { return "" }
        
        let subString = NSString(string: self).substring(from: from)
        return subString
    }
    
    /**
     * 从头开始截取, 截取到 to
     */
    func cca_subsring(to: Int) -> String {
        var to_ = to
        guard to_ > 0 else { return "" }
        if to_ > count { to_ = count }
        
        let subString = NSString(string: self).substring(to: to_)
        return subString
    }
    
    /**
     * 从range.location开始截取 range.length
     */
    func cca_subsring(range: NSRange) -> String {
        var subLength = range.length
        let subLocation = range.location
        guard subLocation >= 0 && subLength > 0 else { return "" }
        
        let subTotal = subLocation + subLength
        if subLocation > count - 1 { return "" }
        if subTotal > count - 1 {
            subLength = count - subLocation
        }
        
        let subString = NSString(string: self).substring(with: NSRange(location: subLocation, length: subLength))
        return subString
    }
    
    /**
     * 从from开始截取 length
     */
    func cca_subsring(from: Int, length: Int) -> String {
        let subString = cca_subsring(range: NSRange(location: from, length: length))
        return subString
    }
}
